package com.mycompany.myapp;

import java.sql.SQLException;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
@Controller
public class SyncTodoController {
	
	@RequestMapping(value = "/SyncTodo", method = RequestMethod.POST)
	public String syncTodos(String data, Model model) throws ClassNotFoundException, SQLException{
		System.out.println("data = " + data);
		int ret = 0;
		int syncLog = 0;
		JSONArray ja = new JSONArray();
		ja = (JSONArray) JSONValue.parse(data); //jsonarray로 변환
		
		for(int i=0; i<ja.size(); i++){
			Gson gson = new Gson();
			SyncData tmp = gson.fromJson(ja.get(i).toString(), SyncData.class); 
			syncLog = tmp.getSyncLog();
			
			if(syncLog==1){
				// createTodo
				Todo newTodo = new Todo(tmp.getPky(),"This is Title",tmp.getContent());	// SyncData -> Todo 
				ret = TodoDAO.createTodo(newTodo);
			}
			else if(syncLog==2){
				//modifyTodo
				Todo newTodo = new Todo(tmp.getPky(),"This is Title2",tmp.getContent());
				ret = TodoDAO.modifyTodo(newTodo);
			}
			else if(syncLog==3){
				// removeTodo
				ret = TodoDAO.removeTodo(tmp.getPky());
			}	
		}
		model.addAttribute("message", ret);
		return "SyncTodo";
	}
}
